﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Provide singleton functionality
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonBehaviour<T> : MonoBehaviour
	where T : SingletonBehaviour<T>
{
	static T instance;

	public static T Inst
	{
		get
		{
			if (instance == null)
			{
				T[] managers = GameObject.FindObjectsOfType (typeof (T)) as T[];
				if (managers.Length > 1)
				{
					Debug.LogError ("You have more than one " + typeof (T).Name + " in the scene. You only need 1, it's a singleton!");
					foreach (T manager in managers)
					{
						Component obj = manager as Component;
						Component.Destroy (obj.gameObject);
					}
					new GameObject (typeof (T).Name, typeof (T));
					managers = GameObject.FindObjectsOfType (typeof (T)) as T[];
				}
				else if (managers.Length == 0)
				{
					new GameObject (typeof (T).Name, typeof (T));
					managers = GameObject.FindObjectsOfType (typeof (T)) as T[];
				}
				if (managers.Length == 1)
				{
					instance = managers[0];
					if (Application.isPlaying)
					{
						MonoBehaviour.DontDestroyOnLoad (instance);
					}
				}
			}
			return instance;
		}
		set { instance = value; }
	}
}
